﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoolCode;
using XNoteBook.Services;
using XNoteBook.Models;
using XNoteBook.Entities;
using XNoteBook.UI.Models;

namespace XNoteBook.UI.Controllers
{
	public class TestController : CoolCode.Web.Mvc.ControllerBase
	{
		private IPostService _PostService;
		public IPostService PostService
		{
			get
			{
				if (_PostService == null)
				{
					_PostService = Digger.Dig<IPostService>();
				}
				return _PostService;
			}
		}

		public ActionResult Index()
		{
			return View();
		}

		public ActionResult JsTree()
		{
			Category model = new Category();
			return View(model);
		}

		[HttpPost]
		public ActionResult JsTree(Category model)
		{
			model.CategoryID = model.CategoryID ?? Util.GenerateUID();
			model.CreateTime = DateTime.Now;
			model.CreateUserID = "Bruce";
			model.CreateUserName = "Bruce Lee";

			string parentID = Request.Form["ParentID"];

			this.PostService.SaveCategory(model, parentID, 0);

			return View(model);
		}

		[HttpPost]
		public ActionResult EditTree(string operation)
		{
			var request = Request.Form;
			string parentID = request["ref"];
			string id = request["id"];
			string title = request["title"];
			string position = request["position"];
			string type = request["type"];
			string copy = request["copy"];

			switch (operation)
			{
				case "move_node":
					TreeCategory node = new TreeCategory();
					node.NodeID = id;
					node.ParentID = parentID;
					node.SortIndex = Convert.ToInt32(position);
					bool isCopy = (copy == "1");
					this.PostService.MoveNode(node, isCopy);
					break;

				case "create_node":
					id = Util.GenerateUID();
					this.PostService.SaveNode(new NodeModel
					{
						NodeID = id,
						Type = Enum<NodeType>.FindByAttachedString(type),
						Title = title,
						ParentID = parentID,
						CreateUserID = User.Identity.Name,
						CreateUserName = User.Identity.Name,
						SortIndex = Convert.ToInt32(position)
					});
					break;

				case "remove_node":
					this.PostService.DeleteNode(id);
					break;

				case "rename_node":
					this.PostService.RenameCategory(new Category
					{
						CategoryID = id,
						Title = title
					});
					break;
			}

			return Json(new { status = 1, id = id });
		}

		public ActionResult GetTreeData(string parentID)
		{
			var model = PostService.GetChildrenNodes(parentID);

			var jsonData = model.Items.Select(c => new
			{
				attr = new
				{
					id = c.NodeID,
					rel = c.Type.GetAttachedString(),//rel = string.IsNullOrEmpty(parentID) ? "drive" : (c.IsCategory ? "folder" : "default"),
					position = c.SortIndex
				},
				data = c.Title,
				state = c.IsLeaf ? "opened" : "closed"
			}).ToList();

			return Json(jsonData, JsonRequestBehavior.AllowGet);
		}
	}
}
